package com.Data;

import java.io.File;
import java.util.ArrayList;

import com.Domain.Channel;
import com.EdificacioAR.DebugLog;
import com.Exceptions.ExternalStorageAccessException;
import com.Exceptions.ExternalStorageException;
import com.Exceptions.ExternalStorageWriteException;

import android.os.Environment;

public class DataLoader {
	
	private static final String APP_PATH = "U_AR_Channels";
	private static final String TAG = "DataLoader";
	
	public static ArrayList<Channel> loadData() throws ExternalStorageException {
		
		ArrayList<Channel> channels = new ArrayList<Channel>();

		// Try to read the home directory of the application
		File rootSD = Environment.getExternalStorageDirectory();
		File appDir = new File(rootSD, APP_PATH);
		DebugLog.LOGD(TAG + " - application directory: " + appDir);
		boolean appDirExists = appDir.exists();
		
		// Check the state of the external storage
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    // We can read and write the media
		    DebugLog.LOGD(TAG + " - Media Mounted");
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    // We can only read the media
		    DebugLog.LOGD(TAG + " - Media Read Only");
		    
		    if (!appDirExists) {
		    	DebugLog.LOGE(TAG + " - Cannot create application directory on the Read Only external storage");
		    	throw new ExternalStorageWriteException();
		    }
		    
		} else {
		    // Something else is wrong. It may be one of many other states, but all we need
		    //  to know is we can neither read nor write
		    DebugLog.LOGD(TAG + " - Cannot read nor write on external storage");
		    throw new ExternalStorageAccessException();
		}
		
		// Create application directory if it doesn't exist
		if (!appDirExists) {
			if (!appDir.mkdirs()) { 
				DebugLog.LOGE(TAG + " - Error creating application home directory");
				throw new ExternalStorageWriteException();
			}
		}
			
		// Read every channel directory and XML within the app directory
		for (File channelFile : appDir.listFiles(new ChannelFileFilter()))
		{
			// Read the XML file with all the channel info
			File xmlFile = channelFile.listFiles(new XMLFileFilter())[0];
						
			Channel c = XMLReader.readXML(xmlFile);
			DebugLog.LOGD(TAG + " - xml channel read: " + c.getName());
			channels.add(c);
		}
		
		return channels;
		
	}
	
	public static String getAppDirectory() {
		return Environment.getExternalStorageDirectory() + "/" + APP_PATH;
	}

}
